//@ts-ignore 引入crypto-js库中的SHA256加密函数
import * as CryptoJS from 'crypto-js.min';

/** 火箭游戏数值种子加密算法 */
export namespace Crypto {
    /** 哈希加密 */
    export function sha256Encrypt(text: string | number): string {
        try {
            return CryptoJS.SHA256(text).toString();
        } catch (error) {
            console.warn('SHA256 encryption failed:', error);
            return '';
        }
    }

    // 密文串
    const ALPHABET = '2YbGWMm0kC6R15QETUwp37qsvDFJtoNguLSZKrdjhHAIPezy8lBf4xXaiVnc9O';
    // 待加密正整数最大值
    const MAXINTNUM = 100000;
    // 加密函数
    export function base62Encode(num: number): string {
        let str = '';
        let value = num;
        do {
            str = ALPHABET[num % 62] + str;
            num = Math.floor(num / 62);
        }
        while (num > 0);
        CC_PREVIEW && console.log(`【base62Encode】Encoded ${value} to String: ${str}`);
        return str;
    }
    // 解密函数
    export function base62Decode(str: string): number {
        let num = 0;
        for (let i = 0; i < str.length; i++) {
            num = num * 62 + ALPHABET.indexOf(str[i]);
        }
        CC_PREVIEW && console.log(`【base62Decode】Decoded ${str} to Number: ${num}`);
        return num;
    }

    /** 实现一个 0.00 ~ 999.99 区间的2位小数加密算法 */
    export function easyEncrypt(value: number): string {
        const intValue = Math.floor(value * 100);
        const v1 = (intValue + MAXINTNUM);
        const v2 = (intValue + MAXINTNUM) * 2;
        const v3 = (intValue + MAXINTNUM) * 3;
        const v4 = (intValue + MAXINTNUM) * 4;
        return base62Encode(v1) + base62Encode(v2) + base62Encode(v3) + base62Encode(v4);
    }

    /** 配套实现 easyEncrypt 反向解密算法 */
    export function easyDecrypt(text: string): string {
        if (text.length === 0) return '0';

        const length = text.length;
        const partLength = Math.floor(length / 4);
        const str1 = text.substring(0, partLength);
        const intValue1 = base62Decode(str1) % MAXINTNUM;

        const dbPartLength = 2 * partLength;
        const str2 = text.substring(partLength, dbPartLength);
        const intValue2 = base62Decode(str2) % MAXINTNUM;

        const length3 = Math.floor((length - dbPartLength) / 2);
        const str3 = text.substring(dbPartLength, dbPartLength + length3);
        const intValue3 = base62Decode(str3) % MAXINTNUM;

        const str4 = text.substring(dbPartLength + length3);
        const intValue4 = base62Decode(str4) % MAXINTNUM;

        const intValue = (intValue1 + intValue2 + intValue3 + intValue4) % MAXINTNUM;
        const value = intValue / 1000;
        return value.toFixed(2);
    }
}
